import React, {PureComponent} from "react";
import {
    View,
    Button,
    SafeAreaView,
    Text,
    StyleSheet,
    Platform,
    NativeModules,
    TextInput,
    ScrollView,
    Dimensions,
    NativeEventEmitter,
    TouchableOpacity,
    ToastAndroid,
    Image,
    DeviceEventEmitter
} from "react-native";
import color from "../../../widget/color";
import {isMobile, isPhoneDigit} from "../../../widget/CommonUtils";
import api from "../../../api/api";
import method from "../../../api/method";
import {fetchPostRequest} from "../../../api/NetworkTool";
import Tips from "react-native-root-tips";
const {width} = Dimensions.get('window')
var Push = NativeModules.PushNative;
const NativeModule = new NativeEventEmitter(Push);

type Props = {
    navigation:any,
}
export default class AddAddressScene extends PureComponent<Props> {

    static navigationOptions = ({navigation}: any) => ({
        headerTintColor: 'rgba(0,0,0,0.8)',
        title: '新建地址',
        headerRight: <Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    });
    // static navigationOptions = ({navigation}) => StackOptions({navigation})

    constructor(props) {
        super(props)
        this.state = {
            address: '',
            receiver: '',
            phone: '',
            detail_address: '',
            address_id: '',
            timerCount: 2,
        }
    }

    componentWillUnmount() {
        //删除监听
        this.subscription.remove()
        this.listener.remove()
    }

    _getNotice(body) {//body 看你传什么
        //一系列操作
        console.log(body['addressId'])
        this.setState({address: body['address'], address_id: body['addressId']});
    }

    componentDidMount() {
        this.subscription = NativeModule.addListener('AddressNot', (data) => this._getNotice(data));
        this.listener = DeviceEventEmitter.addListener('AndroidToRNMessage', this.handleAndroidMessage);
    }

    // handleAndroidMessage(aMessage) {
    //     console.log(aMessage)
    //     ToastAndroid.show(aMessage.result, ToastAndroid.SHORT)
    //     ToastAndroid.show(aMessage.data, ToastAndroid.SHORT)
    //     // this.setState({address: aMessage.result});
    // }

    handleAndroidMessage = (e) => {
        this.setState({
            address: e.result,
            address_id: e.data
        });
        // DeviceEventEmitter.removeListener('onScanningResult',this.onScanningResult);//移除扫描监听
    }

    render() {
        return (
            <SafeAreaView style={{flex:1,backgroundColor:'#f5f5f5'}}>
                <ScrollView style={{backgroundColor:'#f5f5f5'}}>
                    <View
                        style={{flexDirection:'row',width:width,height:53,alignItems:'center',paddingLeft:12,paddingRight:12}}>
                        <Text style={styles.text}>收货人</Text>
                        <TextInput underlineColorAndroid='transparent' onChangeText={(e)=>{this.setState({receiver:e})}} maxLength={5}
                                   style={styles.text_input} placeholderTextColor='#999999'
                                   placeholder='请输入收货人'/>
                    </View>
                    <View style={{backgroundColor:'#DFDFDF',width:width-24,marginLeft:12,height:1}}/>
                    <View
                        style={{flexDirection:'row',width:width,height:53,alignItems:'center',paddingLeft:12,paddingRight:12}}>
                        <Text style={styles.text}>手机号码</Text>
                        <TextInput onEndEditing={()=>{
                            this._onEndEditing()
                        }} underlineColorAndroid='transparent' maxLength={11}
                                   keyboardType='numeric'
                                       onChangeText={(text)=>{this.changeText(text)}}
                                       style={styles.text_input}
                                       placeholderTextColor='#999999' placeholder='请输入11位手机号码'/>
                    </View>
                    <View style={{backgroundColor:'#DFDFDF',width:width-24,marginLeft:12,height:1}}/>
                    <TouchableOpacity onPress={()=>{
                            if (Platform.OS === 'ios'){
                                Push.RNOpenOneVC('测试')
                            }else if(Platform.OS === 'android'){
                                NativeModules.MyNativeModule.callNativeMethod();
                            }

                        }}
                                      style={{flex:1,flexDirection:'row',width:width,height:53,alignItems:'center',paddingLeft:12,paddingRight:12}}>
                        <Text style={styles.text}>所在地区</Text>
                        <TextInput underlineColorAndroid='transparent' style={styles.text_input1} value={this.state.address} editable={false}
                                   placeholderTextColor='#999999' placeholder='请选择'/>
                        <Image style={{width:8,height:13,marginRight:20}} source={require('../../../../res/img/gobal_arrow.png')}/>
                    </TouchableOpacity>
                    <View style={{backgroundColor:'#DFDFDF',width:width-24,marginLeft:12,height:1}}/>
                    <View
                        style={{flexDirection:'row',width:width,height:53,alignItems:'center',paddingLeft:12,paddingRight:12}}>
                        <Text style={styles.text}>详细地址</Text>
                        <TextInput maxLength={32} underlineColorAndroid='transparent' onChangeText={(e)=>{this.setState({detail_address:e})}} style={styles.text_input}
                                   multiline={true} placeholderTextColor='#999999'
                                   placeholder='请输入详细地址'/>
                    </View>
                    <View style={{backgroundColor:'#DFDFDF',width:width-24,marginLeft:12,height:1}}/>
                </ScrollView>
                {this.bao_cun()}

            </SafeAreaView>
        )
    }

    _onEndEditing(){
        if (!isMobile(this.state.phone)) {
            Tips.showWarn('请输入有效的手机号码',{mask:true})
        }
    }
    bao_cun() {
        if (this.state.receiver && this.state.phone && this.state.address && this.state.address_id && this.state.detail_address) {
            return <TouchableOpacity onPress={()=>{this.request_ti_jiao()}} style={styles.enable_bao_cun}>
                <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>保存</Text>
            </TouchableOpacity>
        } else {
            return <View style={styles.un_enable_bao_cun}>
                <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>保存</Text>
            </View>
        }


    }

    request_ti_jiao() {
        if (!isMobile(this.state.phone)) {
            Tips.showWarn('请输入有效的手机号码',{mask:true})
            return
        }
        this.requestCreateAddr()

    }

    requestCreateAddr() {
        let params = {
            regionId: this.state.address_id,
            address: this.state.detail_address,
            receiver: this.state.receiver,
            mobile: this.state.phone,
            isDefault: false,
        }
        fetchPostRequest(api.createUserAddr, method.post, params)
            .then(res => {
                Tips.showSuccess('保存成功！',{mask:true})
                const {goBack, state} = this.props.navigation;
                state.params.callback('回调参数');
                goBack();
            }).catch(err => {
            console.log(err)
        })


    }

    changeText(text) {
        if (!isPhoneDigit(text)) {
            Tips.showWarn('请输入有效的手机号码',{mask:true})
            return
        }
        this.setState({phone: text})
    }
}

const styles = StyleSheet.create({
    text: {
        fontSize: 14,
        color: '#333333',
        width: 60,
    },
    text_input: {
        fontSize: 14,
        color: '#111111',
        marginLeft: 21,
        width: (width - 93 - 12),
        height:40
    },
    text_input1: {
        fontSize: 14,
        color: '#111111',
        marginLeft: 21,
        width: (width - 93 - 30),
        height:40
    },
    enable_bao_cun: {
        height: 50,
        backgroundColor: color.globalMainColor,
        alignItems: 'center',
        justifyContent: "center",
    },
    un_enable_bao_cun: {
        height: 50,
        backgroundColor: '#BBBABA',
        alignItems: 'center',
        justifyContent: "center",
    }
})